<?php
/**
 * Created by PhpStorm.
 * User: lanlc
 * Date: 17-1-13
 * Time: 下午2:29
 */

namespace app\backend\controller;

use app\backend\model\Bank;
use app\backend\model\BatchPayment;
use app\backend\model\ExcelFile;
use app\backend\model\JournalOnline;
use app\backend\model\Lease;
use app\backend\model\Member;
use app\backend\model\MessageTemplate;
use app\backend\model\PayNotice;
use app\backend\model\Reconciliation;
use Business\Business;
use Business\TongLianBatchPayment\BatchTranx;
use Business\TongLianBatchPayment\cURL;
use think\Controller;
use app\backend\model\Contract;
use app\backend\model\BillManager;
use app\backend\model\Trust;
use app\backend\model\Building;

//权限判断
if (!defined('ZFT_CLI')) {
    exit('Access Deny');
}

class CrontabController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

//    /**
//     * 生成应付订单-类型月
//     * @date   2017-01-13
//     * @author Lanlc
//     *
//     * @return
//     */
//    public function runMonthPayBill()
//    {
//        $contractModel = new Lease();
//        $billModel = new BillManager();
//        $flag = true;
//        $page = 1;
//        $pageSize = 500;
//        $field = '*';
//        $billData = [];
//        $tempContractId = [];
//        $montyMark = date('Ymd');  //月账单标记  签订合同的时候记得加上1，启动日
//        $allDate = date('t');//获取本月有几天
//        //结束时间大于等于本月第一天的有可能有账单生成
//        $where = ['status' => 1, 'charge_type' => 2, 'cycle_mark' => ['ELT', $montyMark], 'end_time' => ['EGT', strtotime(date('Ym') . '01')]];
//        while ($flag) {
//            $data = $contractModel->getRunningContract($where, $page, $pageSize, $field);
//            //var_dump($data);die;
//            if ($data) {
//                ++$page;
//                foreach ($data as $key => $val) {
//
//                    //如果不是账单日则跳过
//                    if ((date('d', time()) != $val['billing_day'])) {
//                        if ($allDate<$val['billing_day'] && $allDate == date('d', time())) {
//                            //这种情况不能跳过(比如账单日是31号，但本月只有30号，默认本月最后一天跑)
//                        } else {
//                            continue;
//                        }
//                    }
//
//                    if ($val['end_time'] < time()) {
//                        //是账单日，但租期截止时间小于这个时间，没有账单生成
//                        continue;
//                    }
//                    //假如3月15日的账单周期，生成3.16-4.15的账单
//                    $endCycle = date('Ymd', strtotime('+1 month'));
//                    $beginCycle   = date('Ymd', strtotime('+1 day'));
//                    $tempContractId[] = $val['id'];
//                    //echo $endCycle.'--'.$beginCycle;die;
//                    $tempData['ordernum']     = $val['ordernum'];
//                    $tempData['building_id']  = $val['building_id'];
//                    $tempData['house_id']     = $val['house_number'];
//                    $tempData['charge_out']   = date('Ymd');
//                    $tempData['type']         = $val['charge_type'];
//                    $tempData['begin_cycle']  = $beginCycle;
//                    $tempData['end_cycle']    = $endCycle;
//                    $tempData['tenant_id']    = $val['tenant_id'];//租户
//                    $tempData['status']       = 0;
//                    $tempData['bill_type']    = $val['ordermode'];
//                    $tempData['time']         = time();
//                    $tempData['bill_time']    = date('Ym');
//
//                    $tempWhere = ['ordernum' => $val['ordernum']];
//                    $feeData = $contractModel->getContractFee($tempWhere, '*');
//
//                    if ($feeData) {     //每个收费用户的每种收费类型都生成一个订单数据
//                        foreach ($feeData as $v) {
//                            $tempData['type_money'] = $v['type'];           //收费类型：1租金，2物业，3水, 4电, 5公摊水，6公摊电
//                            $tempData['money'] = $v['fee'] * $v['ratio']/100; //费用乘以收费占比
//                            $tempData['owner_id'] = $v['owner_id'];//分别保存每个用户的每个收费账单
//                            $billData[] = $tempData;
//                        }
//                    }
//                }
//
//                if ($billData) {
//                    $tempContractId = array_unique($tempContractId);
//                   // zft_log('pay_bill_rec', print_r($billData, true));
//                    $billModel->insertPayBill($billData);
//                    $billData = [];
//
//                    //更新下次的启动日
//                    $contractModel->updateContract(['id' => ['IN', $tempContractId]], ['cycle_mark' => date('Ymd', strtotime('+1 month'))]);
//                    $tempContractId = [];
//                } else {
//                    exit('running is finish!');
//                }
//            } else {
//                exit('running is finish!');
//            }
//        }
//    }
//
//
//    /**
//     * 生成应付订单-类型年
//     * @date   2017-01-13
//     * @author Lanlc
//     *
//     * 后期加上账单周期
//     *
//     * @return
//     */
//    public function runYearPayBill()
//    {
//        $contractModel = new Lease();
//        $billModel = new BillManager();
//        $flag = true;
//        $page = 1;
//        $pageSize = 500;
//        $field = '*';
//        $billData = [];
//        $tempContractId = [];
//        $yearMark = date('Ymd');  //年账单标记，签订合同的时候，记得+1启动日
//        $where = ['status' => 1, 'charge_type' => 1, 'cycle_mark' => ['ELT', $yearMark],'begin_time' => ['ELT', time()]];//合同开始时间小于当前时间
//        while ($flag) {
//            $data = $contractModel->getRunningContract($where, $page, $pageSize, $field);
//            //var_dump($data);die;
//            if ($data) {
//                ++$page;
//                foreach ($data as $key => $val) {
//                    //如果不是账单日则跳过
//                    if (date('md', time()) != $val['billing_day']) {
//                        continue;
//                    }
//                    $endCycle = $val['cycle_mark']-1;
//                    $beginCycle   = date('Ymd', strtotime('-1 year'));
//                    $tempContractId[] = $val['id'];
//                    $tempData['ordernum']     = $val['ordernum'];
//                    $tempData['building_id']  = $val['building_id'];
//                    $tempData['house_id']     = $val['house_number'];
//                    $tempData['charge_out']   = date('Ymd');
//                    $tempData['type']         = $val['charge_type'];
//                    $tempData['begin_cycle']  = $beginCycle;
//                    $tempData['end_cycle']    = $endCycle;
//                    $tempData['tenant_id']    = $val['tenant_id'];
//                    $tempData['status']       = 1;
//                    $tempData['bill_type']    = $val['ordermode'];
//                    $tempData['time']         = time();
//                    $tempData['bill_time']    = date('Y');
//                    $tempWhere = ['ordernum' => $val['ordernum']];
//
//                    $feeData = $contractModel->getContractFee($tempWhere, '*');
//                    if ($feeData) {
//                        foreach ($feeData as $v) {
//                            $tempData['type_money'] = $v['type'];            //收费类型：1租金，2物业，3水, 4电, 5公摊水，6公摊电
//                            $tempData['money'] = $v['fee'] * $v['ratio']/100; //费用乘以收费占比
//                            $tempData['owner_id'] = $v['owner_id'];//分别保存每个用户的每个收费账单
//                            $billData[] = $tempData;
//                        }
//                    }
//                }
//                //var_dump($billData);die;
//                if ($billData) {
//                    $tempContractId = array_unique($tempContractId);
//                    // zft_log('pay_bill_rec', print_r($billData, true));
//                    $billModel->insertPayBill($billData);
//                    $billData = [];
//
//                    //更新下次的启动日
//                    $contractModel->updateContract(['id' => ['IN', $tempContractId]], ['cycle_mark' => date('Ymd', strtotime('+1 month'))]);
//                    $tempContractId = [];
//                } else {
//                    exit('running is finish!');
//                }
//            } else {
//                exit('running is finish!');
//            }
//        }
//    }

    /**
     * 检测更新合同状态
     * @date   2017-01-16
     * @author Lanlc
     *
     *
     * @return
     */
    public function expiredContract()
    {
        $contractModel = new Lease();
        $buildingModel = new Building();
        $flag = true;
        $page = 1;
        $pageSize = 500;
        $time = time();
        $where = ['status' => 1];
        $expiredOrderNum = [];
        while ($flag) {
            $data = $contractModel->getRunningContract($where, $page, $pageSize);
            if ($data) {
                ++$page;

                foreach ($data as $key => $val) {
                    if (strtotime($val['end_time']) <= $time) {
                        $expiredOrderNum[] = $val['ordernum'];
                        //$houseIds[] = $val['house_number'];
                    }
                }

                if ($expiredOrderNum) {
                    //获取对应房源信息
                    $detail = $contractModel->getLeaseExtByOrderNum($expiredOrderNum, 'ordernum, house_number, room');
                    $houseNumber = array_column($detail, 'house_number');
                    //更新房源状态
                    $updateResult3 = $buildingModel->updateHouse(['status' => 2], ['house_number' => ['IN', $houseNumber]]);
                    if (!$updateResult3) {
                        zft_log('expiredContract_fail', print_r($buildingModel->getLastSql(), true));
                    }

                    /*  //先判断对应的合同是否账单已经结算清楚
                      $billModel = new BillManager();
                      $billList = $billModel->getPayBillList(['ordernum' => ['in', $expiredOrderNum]], '*');
                      if ($billList) {
                          $orderNumbers = array_unique(array_column($billList, 'ordernum'));
                          //.....
                      }*/

                    //更新合同状态
                    $updateResult = $contractModel->updateContract(['ordernum' => ['IN', $expiredOrderNum]], ['status' => 0]);
                    if (!$updateResult) {
                        zft_log('expiredContract_fail', print_r($contractModel->getLastSql(), true));
                    }
                    $updateResult2  =$contractModel->updateContractExt(['ordernum' => ['IN', $expiredOrderNum]], ['status' => 0]);
                    if (!$updateResult2) {
                        zft_log('expiredContract_fail', print_r($contractModel->getLastSql(), true));
                    }
                    $expiredOrderNum = [];
                    $houseNumber = [];
                }
            } else {
                exit('running is finish!');
            }
        }
    }

    /**
     * 生成托管订单数据-月
     * @date   2017-01-23
     * @author Lanlc
     *
     *
     * @return
     */
    public function runTrustMonthBill()
    {
        $trustModel    = new Trust();
        $buildingModel = new Building();
        $billModel     = new BillManager();

        //$payBillMonth = date('Ym', strtotime('-1 month'));
        $payBillMonth = date('Ym'); //应付账单的月份，用于准确跟踪
        $field        = '*';
        $page         = 1;
        $pageSize     = 500;
        $flag         = true;
        $insertData   = [];
        $trustIds     = [];

        $cycleMark = date('Ymd');    //生成账单标记
        $allDate   = date('t');//获取本月有几天
        $where     = ['status' => 1, 'cycle_mark' => ['ELT', $cycleMark], 'settle_type' => 2, 'endtime' => ['EGT', strtotime(date('Ym') . '01')]];

        while ($flag) {
            $offSet = ($page - 1) * $pageSize;
            $data   = $trustModel->getTrust($where, $field, $offSet, $pageSize);  //获取满足条件的托管合约数据
            //var_dump($data);die;
            if ($data) {
                ++$page;
                foreach ($data as $key => $val) {
                    //如果不是账单日则跳过
                    if ((date('d', time()) != $val['billing_date'])) {
                        if ($allDate < $val['billing_date'] && $allDate == date('d', time())) {
                            //这种情况不能跳过(比如账单日是31号，但本月只有30号，默认本月最后一天跑)
                        } else {
                            continue;
                        }
                    }

                    if ($val['endtime'] < time()) {
                        //是账单日，但租期截止时间小于这个时间，没有账单生成(比如租期到期时间是3.15 账单周期是20号，不会生成下月的)
                        continue;
                    }
                    //假如3月15日的账单周期，生成3.16-4.15的账单
                    $endCycle     = date('Ymd', strtotime('+1 month'));
                    $beginCycle   = date('Ymd', strtotime('+1 day'));
                    $trustIds[]   = $val['id'];
                    $tempHouseIds = [];
                    $houseInfo    = $buildingModel->getHouseInfoByUser($val['owner_id'], $val['building_id'], 'house_number');
                    $tempHouseIds = array_column($houseInfo, 'house_number');//获取业主托管的全部房源数据
                    //var_dump($tempHouseIds);die;

                    $allMoney = $billModel->getRentedCntMoney($tempHouseIds, $payBillMonth, 1);   //从应付账单里获取全部应收租金
                    $allMoney = $allMoney['sum'];
                    //var_dump($allMoney);die;

                    $payBillData = $billModel->getPayedBill($val['building_id'], 1, $payBillMonth, 1, $tempHouseIds);  //获取对于这个业主的已经付款房租的账单
                    $payCnt      = count($payBillData);

                    $payMoney = 0;      //初始化实收租金
                    if ($payCnt) {
                        foreach ($payBillData as $k => $v) {
                            $payMoney += $v['money'];
                        }
                    }

                    if ($allMoney <= $val['dozen_money']) {
                        //应收租金小于保底金额则不清算
                        $ratio            = 0;             //分成比例为空
                        $allMoney         = $val['dozen_money'];//没达到保底金额的时候，应收租金为保底金额
                        $shouldShareMoney = 0;  //应收分成金额为0
                        $realShareMoney   = 0;    //实收分成金额为0
                        $pay_state        = 1;         //已结算
                    } else {
                        $shareMoney = $allMoney - $val['dozen_money'];  //分成金额
                        $rentHouse  = $buildingModel->getRentHouseCnt($val['building_id'], $val['owner_id'], 1, 1);  //获取这个业主托管的房源出租中的总数
                        $trustHouse = $buildingModel->getRentHouseCnt($val['building_id'], $val['owner_id'], 1, 0);    //获取这个业主托管的房源的总数
                        $rentRatio  = floor(($rentHouse['cnt'] / $trustHouse['cnt']) * 100);        //取得出租率
                        $ruleData   = $billModel->getShareData($val['orderid'], $rentRatio);     //获取分成比例
                        //如有有达到分成比例要求
                        if ($ruleData) {
                            //获取是否全部缴费（缴费订单总数等于出租中的房源总数）
                            if ($payCnt == $rentHouse['cnt']) {
                                $pay_state      = 1;
                                $realShareMoney = intval($shareMoney * $ruleData['split_ratio'] / 100); //实收分成金额
                            } else {
                                $pay_state      = 0;
                                $realShareMoney = 0;    //实收分成金额为0，待用户全部缴清房租再分成
                            }

                            $ratio            = round($ruleData['split_ratio'] / 10, 1);                 //分成比例
                            $shouldShareMoney = intval($shareMoney * $ruleData['split_ratio'] / 100);   //应收分成金额，全部缴清房租后实收分成金额的依据
                        } else {                    //未达成任意出租率
                            $ratio            = 0;             //分成比例为空
                            $shouldShareMoney = 0;  //应收分成金额为0
                            $realShareMoney   = 0;    //实收分成金额为0
                            $pay_state        = 1;         //已结算
                        }
                    }

                    $rationOwner = round(10 - $ratio, 1);
                    $ratio       = round($ratio, 1);
                    $ratio       = $ratio . ':' . $rationOwner;

                    $trustBillData = [
                        'owner_id'         => $val['owner_id'],
                        'tenant_id'        => $val['trust_id'],
                        'bill_time'        => date('Ymd'),
                        'ordernum'         => $val['orderid'],
                        'begin_cycle'      => $beginCycle,
                        'end_cycle'        => $endCycle,
                        'ratio'            => $ratio,                 //分成比例
                        'rent_rate'        => $rentRatio,             //出租率 @wuhao 3-27新增
                        'should_rent'      => $allMoney,              //应收租金
                        'real_rent'        => $payMoney,              //实收租金
                        'share_money'      => $shouldShareMoney,      //应收分成金额
                        'real_share_money' => $realShareMoney,   //实收分成金额
                        'status'           => 0,                     //结算状态
                        'pay_state'        => $pay_state,            //缴费状态
                        'building_id'      => $val['building_id'], //楼宇ID
                        'pay_bill_time'    => $payBillMonth,       //应付账单的出账月份
                    ];
                    $insertData[]  = $trustBillData;
                }
                // print_r($insertData);die;
                if ($insertData) {
                    //zft_log('inset_trust_bill', print_r($trustBillData, true));
                    $billModel->insetTrustBill($insertData);
                    $insertData = [];
                }
                $trustModel->updateTrustOrder(['id' => ['IN', $trustIds]], ['cycle_mark' => date('Ymd', strtotime('+1 month'))]);
                $trustIds = [];
            } else {
                exit('running is finish!');
            }
        }
    }

    /**
     * 生成托管订单数据-年
     * @date   2017-01-23
     * @author Lanlc
     *
     *
     * @return
     */
    public function runTrustYearBill()
    {
        $trustModel    = new Trust();
        $buildingModel = new Building();
        $billModel     = new BillManager();

        $beginCycle = date('Ymd', strtotime('-1 month'));
        $endCycle   = date('Ymd', strtotime('-1 day'));

        //$payBillYear = date('Ym', strtotime('-1 year'));
        $payBillYear = date('Y'); //应付账单的月份，用于准确跟踪
        $field       = 'id, building_id, dozen_money, orderid, owner_id, trust_id';
        $page        = 1;
        $pageSize    = 500;
        $flag        = true;
        $insertData  = [];
        $trustIds    = [];

        $cycleMark = date('Ymd');    //生成账单标记
        $where     = ['status' => 1, 'cycle_mark' => ['EQ', $cycleMark], 'settle_type' => 1, 'begintime' => ['ELT', time()]];

        while ($flag) {
            $offSet = ($page - 1) * $pageSize;
            $data   = $trustModel->getTrust($where, $field, $offSet, $pageSize);  //获取满足条件的托管合约数据
            //var_dump($data);die;
            if ($data) {
                ++$page;
                foreach ($data as $key => $val) {
                    $trustIds[]   = $val['id'];
                    $tempHouseIds = [];
                    $houseInfo    = $buildingModel->getHouseInfoByUser($val['owner_id'], $val['building_id'], 'house_number');
                    $tempHouseIds = array_column($houseInfo, 'house_number');//获取业主托管的全部房源数据

                    $allMoney = $billModel->getRentedCntMoney($tempHouseIds, $payBillYear, 1);   //从应付账单里获取全部应收租金
                    $allMoney = $allMoney['sum'];

                    $payBillData = $billModel->getPayedBill($val['building_id'], 1, $payBillYear, 1, $tempHouseIds);  //获取已经付款房租的账单
                    $payCnt      = count($payBillData);

                    $payMoney = 0;      //初始化实收租金
                    if ($payCnt) {
                        foreach ($payBillData as $k => $v) {
                            $payMoney += $v['money'];
                        }
                    }

                    if ($allMoney <= $val['dozen_money']) {
                        //应收租金小于保底金额则不清算
                        $ratio            = 0;             //分成比例为空
                        $allMoney         = $val['dozen_money'];//没达到保底金额的时候，应收租金为保底金额
                        $shouldShareMoney = 0;  //应收分成金额为0
                        $realShareMoney   = 0;    //实收分成金额为0
                        $pay_state        = 1;         //已结算
                    } else {
                        $shareMoney = $allMoney - $val['dozen_money'];  //分成金额
                        $rentHouse  = $buildingModel->getRentHouseCnt($val['building_id'], $val['owner_id'], 1, 1);  //获取这个业主托管的房源出租中的总数
                        $trustHouse = $buildingModel->getRentHouseCnt($val['building_id'], $val['owner_id'], 1, 0);    //获取这个业主托管的房源的总数
                        $rentRatio  = floor(($rentHouse['cnt'] / $trustHouse['cnt']) * 100);        //取得出租率

                        $ruleData = $billModel->getShareData($val['orderid'], $rentRatio);     //获取分成比例
                        //如有有达到分成比例要求
                        if ($ruleData) {
                            //获取是否全部缴费（缴费订单总数等于出租中的房源总数）
                            if ($payCnt == $rentHouse['cnt']) {
                                $pay_state      = 1;
                                $realShareMoney = intval($shareMoney * $ruleData['split_ratio'] / 100); //实收分成金额
                            } else {
                                $pay_state      = 0;
                                $realShareMoney = 0;    //实收分成金额为0，待用户全部缴清房租再分成
                            }

                            $ratio            = round($ruleData['split_ratio'] / 10, 1);                 //分成比例
                            $shouldShareMoney = intval($shareMoney * $ruleData['split_ratio'] / 100);   //应收分成金额，全部缴清房租后实收分成金额的依据
                        } else {                    //未达成任意出租率
                            $ratio            = 0;             //分成比例为空
                            $shouldShareMoney = 0;  //应收分成金额为0
                            $realShareMoney   = 0;    //实收分成金额为0
                            $pay_state        = 1;            //已结算
                        }
                    }

                    $rationOwner = round(10-$ratio, 1);
                    $ratio = round($ratio, 1);
                    $ratio = $ratio. ':' . $rationOwner;

                    $trustBillData = [
                        'owner_id'         => $val['owner_id'],
                        'tenant_id'        => $val['trust_id'],
                        'bill_time'        => date('Ymd'),
                        'ordernum'         => $val['orderid'],
                        'begin_cycle'      => $beginCycle,
                        'end_cycle'        => $endCycle,
                        'ratio'            => $ratio,                 //分成比例
                        'rent_rate'        => $rentRatio,             //出租率
                        'should_rent'      => $allMoney,              //应收租金
                        'real_rent'        => $payMoney,              //实收租金
                        'share_money'      => $shouldShareMoney,      //应收分成金额
                        'real_share_money' => $realShareMoney,   //实收分成金额
                        'status'           => 0,                      //结算状态
                        'pay_state'        => $pay_state,             //缴费状态
                        'building_id'      => $val['building_id'], //楼宇ID
                        'pay_bill_time'    => $payBillYear,       //应付账单的出账月份
                    ];
                    $insertData[]  = $trustBillData;
                }
                // print_r($insertData);die;
                if ($insertData) {
                    //zft_log('inset_trust_bill', print_r($trustBillData, true));
                    $billModel->insetTrustBill($insertData);
                    $insertData = [];
                }
                $trustModel->updateTrustOrder(['id'=> ['IN' ,$trustIds]], ['cycle_mark' => date('Ymd', strtotime('+1 year'))]);
                $trustIds = [];
            } else {
                exit('running is finish!');
            }
        }
    }

    /**
     * 定时运行未结算的托管订单
     * @date   2017-01-23
     * @author Lanlc
     *
     *
     * @return
     */
    public function runUnSettleTrustBill()
    {
        $billModel     = new BillManager();
        $buildingModel = new Building();
        $where         = ['pay_state' => 0, 'is_delete' => 0];
        $flag          = true;
        $page          = 1;
        $pageSize      = 500;
        $field         = 'id, building_id, pay_bill_time, owner_id';
        $trustIds      = [];
        while ($flag) {
            $offSet = ($page-1) * $pageSize;
            $data = $billModel->getTrustBill($where, $field, $offSet, $pageSize);
            if ($data) {
                ++$page;
                foreach ($data as $key => $val) {
                    //先获取托管的房源数组
                    $houseInfo    = $buildingModel->getHouseInfoByUser($val['owner_id'], $val['building_id'], 'house_number');
                    $tempHouseIds = array_column($houseInfo, 'house_number');

                    $payBillData = $billModel->getPayedBill($val['building_id'], 0, $val['pay_bill_time'], 1, $tempHouseIds);  //获取未结算的
                    if ($payBillData) {    //如果还有未计算的
                        continue;
                    } else {
                        $trustIds[] = $val['id'];
                    }
                }
                if ($trustIds) {
                    $billModel->updateTrustBill(['id' => ['IN', $trustIds]], ['pay_state' => 1, 'real_share_money' => ['exp', 'share_money'], 'real_rent' => ['exp', 'should_rent']]);
                    //zft_log('update_trust_bill', print_r($billModel->getLastSql(), true));
                    $trustIds = [];
                }
            } else {
                exit('running is finish!');
            }
        }
    }

    /**
     * 生成租赁催缴消息队列
     * @date   2017-04-20
     * @author wuhao
     */
    public function addPayLeaseNoticeList()
    {
        $payNoticeModel = new PayNotice();
        $tplModel       = new MessageTemplate();
        $billModel      = new BillManager();
        $leaseModel     = new Lease();

        //获取租赁催缴配置
        $tplInfo = $tplModel->getTemplateByPayOrIncome(1, 1, 1);
        if (!$tplInfo) {
            exit('模板未配置');
        }
        $page       = 1;
        $pageSize   = 500;
        $insertData = [];
        $pre = '【租付通】租赁缴费，账单周期';
        $rooms='房号';
        $totalPre = '总金额为';
        $zd='账单明细';
        $after = '请登录www.louxiaomei.com进行缴费';
        while(1) {
            //获取还未生成的用户消息模板
            $tmpList = $payNoticeModel->getTemplate(time(), 0, $page, $pageSize);

            if ($tmpList) {
                ++$page;
                $idArray     = [];
                foreach ($tmpList as $k => $v) {
//                    if ($v['building_id'] == 93) {
//                        continue;
//                    }
                    $idArray[] = $v['id'];
                    //获取对应的财务联系人电话
                    $financeMobile = $leaseModel->getLeaseByOrderNum($v['ordernum'], 'finance_mobile');
                    //获取这个用户在这个时间段内未支付的账单
                    $billInfo = $billModel->getPayBillInfo(['tenant_id' => $v['mid'], 'ordernum' => $v['ordernum'], 'begin_cycle' => $v['begin_cycle'],
                                                            'end_cycle' => $v['end_cycle'], 'status' => 0, 'is_delete' => 0], 'money, type_money');
                    if ($billInfo) {
//                        if ($billInfo['building_id'] == 93) {
//                            continue;
//                        }
                        $detail = '';
                        //获取对应房号信息
                        $room = $leaseModel->getLeaseExtByOrderNum($v['ordernum'], 'room');
                        $roomstr = '';
                        foreach ($room as $r) {
                            $roomstr.=$r['room'].',';
                        }
                        $roomstr = rtrim($roomstr, ',');


                        $detail = $pre.$v['begin_cycle'].'~'.$v['end_cycle'].'，'.$rooms.$roomstr.'，';

                        //详情判断
                        $typeMoney = [];
                        foreach ($billInfo as $item) {
                            if (isset($typeMoney[$item['type_money']])) {//存在这个类型的金额有多个收费对象
                                $typeMoney[$item['type_money']] += $item['money'];
                            } else {
                                $typeMoney[$item['type_money']] = $item['money'];
                            }
                        }
                        $moneyDetail = '';
                        foreach ($typeMoney as $key => $tm) {
                            $type  = getMoneyType($key);
                            $money = yuan($tm);
                            $moneyDetail .= $type . ' ' . $money . '元,';
                            unset($type, $money);
                        }
                        $moneyDetail = trim($moneyDetail, ',');
                        //总金额
                        $total = 0;
                        foreach ($billInfo as $item) {
                            $total += $item['money'];
                        }

                        //短信详情保存
                        $detail.= $totalPre.yuan($total).'元，'.$zd.rtrim($moneyDetail).'。'.$after;

                        $insert = [
                            'mid'           => $v['mid'],
                            'contract_type' => $tplInfo[0]['contract_type'],
                            'ordernum'      => $v['ordernum'],
                            'building_id'   => $v['building_id'],
                            'mobile'        => $financeMobile['finance_mobile'],
                            'begin_cycle'   => $v['begin_cycle'],
                            'end_cycle'     => $v['end_cycle'],
                            'message_type'  => $tplInfo[0]['message_type'],
                            'event_type'    => $tplInfo[0]['event_type'],
                            'notify_method' => $tplInfo[0]['notify_method'],
                            'send_type'     => $tplInfo[0]['send_type'],
                            'report_time'   => $v['report_time'],
                            'priority'      => $v['priority'],
                            //'room'          => $rooms,
                            'total_money'   => $total,
                            'detail'        => $detail,
                            'money_detail'  => $moneyDetail,
                            'send_time'     => 0,
                            'send_status'   => 0,
                        ];
                        $insertData[] = $insert;
                    }
                }

                //插入到消息队列里
                if ($insertData) {

                    if ($payNoticeModel->addNoticeList($insertData)) {
                        //更新消息模板的状态为已生成对列
                        $res = $payNoticeModel->updateTemplateStatus($idArray, 1);
                        if (!$res) {
                            zft_log('payNotice/updateTemplate', $payNoticeModel->getLastSql());
                        }
                    } else {
                        zft_log('payNotice/addList', $payNoticeModel->getLastSql());
                    }

                } else {
                    exit('running is finish!');
                }
            } else {
                exit('running is finish!');
            }
        }
    }

    /**
     * 发送租赁催缴消息队列(每天9点跑)
     * @date   2017-04-25
     * @author wuhao
     *
     */
    public function sendPayLeaseNoticeList()
    {
        $payNoticeModel = new PayNotice();
        $tplModel       = new MessageTemplate();
        $business       = new Business();
        //获取租赁催缴配置
        $tplInfo = $tplModel->getTemplateByPayOrIncome(1, 1, 1);
        if (!$tplInfo) {
            exit('模板未配置');
        }
        $content = json_decode($tplInfo[0]['content'], true);
        $page       = 1;
        $pageSize   = 500;
        $leaseModel = new Lease();
        while(1) {
            //获取还未发送的用户消息队列
            $tmpList = $payNoticeModel->getNoticeList(time(), 1,  1,  0, $page, $pageSize);
            if ($tmpList) {
                $orderArr = array_column($tmpList, 'ordernum');
                //获取房号信息
                //获取这些合同对应的房源编号
                $roomArr = $leaseModel->getLeaseExtByOrderNum($orderArr, 'ordernum, room');
                $idArr = [];
                $history = [];
                ++$page;
                foreach ($tmpList as $key => $t) {//循环发送给每个用户
                    $room = '';
                    foreach ($roomArr as $r) {
                        if ($r['ordernum'] == $t['ordernum']) {
                            $room .= $r['room'];
                        } else {
                            continue;
                        }
                    }
                    $datas[0] = $tplInfo[0]['title'];
                    $datas[1] = $datas[2] = $datas[3] = $datas[4] = '';
                    $datas[1] = $t['begin_cycle'].'~'.$t['end_cycle'];
                    $datas[2] = rtrim($room, ',');
                    $datas[3] = yuan($t['total_money']).'元';
                    $datas[4] = $t['money_detail'];

                    if (strtotime($t['end_cycle']) < time()) {
                        //历史数据不发送
                        $history[] = $t['id'];
                    } else {
                        //dd($datas);
                        $res = $business->sendPayNotice($t['mobile'], $datas, $content, 1);
                        if ($res['code'] == 200) {//发送成功
                            $idArr[] = $t['id'];
                        }
                    }
                }

                if ($idArr) {//更新这些发送成功的短信状态
                    $updateStatus = $payNoticeModel->updateNoticeListStatus($idArr, time(), 1);
                    if (!$updateStatus) {
                        zft_log('payNotice/updateList', $payNoticeModel->getLastSql());
                    }
                    unset($idArr);
                }

                if ($history) {//更新不发送的短信状态
                    $updateStatus = $payNoticeModel->updateNoticeListStatus($history, time(), 2);
                    if (!$updateStatus) {
                        zft_log('payNotice/updateList', $payNoticeModel->getLastSql());
                    }
                    unset($history);
                }
            } else { //没有队列了
                exit('running is finish!');
            }
        }
    }

    /**
     * 删除错误模板文件及其记录信息
     * @date   2017-06-07
     * @author wuhao
     *
     */
    public function deleteWrongModel()
    {
        $time = date('Y/m', strtotime('-2month'));
        //删除目录
        $lastPath = EXCEL_IMPORT_DIR.'property_manager/wrong/'.$time;
        delDirAndFile($lastPath, true);
        //删除记录
        $fileModel = new ExcelFile();
        $lastMonth = date('Y-m', strtotime('-1month'));
        $lastTwoMonth = date('Y-m', strtotime('-2month'));
        $size = 500;
        $page = 1;
        while (true) {
            //先获取文件信息
            $fileInfo = $fileModel->getDeleteFile($lastTwoMonth, $lastMonth, $page, $size);
            if ($fileInfo) {
                $page++;
                $idArr = array_column($fileInfo, 'id');
                $urlArr = array_column($fileInfo, 'url');
                foreach ($urlArr as $k => $v) {
                    //获取这个文件的地址,将主域名替换成目录名
                    $urlArr[$k] = str_replace(MAIN_DOMAIN, EXCEL_REMOVE_DIR, $v);
                    //删除文件
                    @unlink($urlArr[$k]);
                }
                $res = $fileModel->deleteWrongModelFile($idArr);
                if (!$res) {
                    zft_log('file', $fileModel->getLastSql());
                }
            } else {
                exit('finish');
            }
        }
    }

    /**
     * @comment 通联批量代付
     * @author wuhao
     */
    public function tonglianPay()
    {
        $batchTranx   = new BatchTranx();
        $batchPayment = new BatchPayment();
        $bank         = new Bank();

        $yesterday = date('Ymd', strtotime('-1 day'));
        $where     = ['pay_time' => $yesterday, 'status' => 0];
        $list      = $batchPayment->getList($where);
        if (!$list) {
            exit('无数据');
        }
        $config = parse_ini_file(HTML_DIR.'/extend/Business/TongLianBatchPayment/data/config.ini', true);
        //商户id
        $merId = $config[ENV]['merId'];
        //$reqsn       = $merId . $yesterday . genRandomNum(7);
        $midArr      = array_unique(array_column($list, 'mid'));
        $bankInfo    = $bank->getBankCardByMid($midArr);

        $i=1;
        $memberInfo = [];//保存信息
        foreach ($bankInfo as $b) {
            foreach ($midArr as $m) {
                if ($m == $b['mid']) {
                    $memberInfo[] = [
                        'SN'              => '0',
                        'E_USER_CODE'     => $m,
                        'BANK_CODE'       => '0'.$b['bank_code'],
                        'ACCOUNT_TYPE'    => '00',
                        'ACCOUNT_NO'      => $b['bank'],
                        'ACCOUNT_NAME'    => $b['username'],
                        'PROVINCE'        => '',
                        'CITY'            => '',
                        'ACCOUNT_PROP'    => '0',
                        'AMOUNT'          => 0,   //实际提现金额 （扣除手续费和每笔1元手续费）
                        'CURRENCY'        => 'CNY',
                        'ID_TYPE'         => '',
                        'ID'              => '',
                        'TEL'             => '',
                        'CUST_USERID'     => $m,
                        'REMARK'          => '备注信息1',
                        'SETTACCT'        => '',
                        'SETTGROUPFLAG'   => '',
                        'SUMMARY'         => '',
                        'PROTOCOL'        => 0,  //备注字段， 提现金额
                    ];
                    $i++;
                    break;
                }
            }
        }

        foreach ($list as $l) {
            foreach ($memberInfo  as $k => $m) {
                if ($l['mid'] == $m['CUST_USERID']) {
                    $memberInfo[$k]['AMOUNT'] += $l['actual_money'];
                    $memberInfo[$k]['PROTOCOL'] += $l['money'];
                }
            }
        }

        //减去每笔1元的手续费
        foreach ($memberInfo as $a => $b) {
            if ($b['AMOUNT'] -100 <=0) {
                zft_log('batchPayment', '用户id'.$m['CUST_USERID'].'提现失败，金额'.intval($b['AMOUNT']/100).'小于手续费1元');
                unset($memberInfo[$a]); //删除提现金额小于1元的
            } else {
                $memberInfo[$a]['AMOUNT'] = $b['AMOUNT'] - 100;
            }
        }

        $memberInfo = array_merge($memberInfo);


        /*        $cntItem = count($memberInfo);
                $cntMoney = 0;
                foreach ($memberInfo as $m) {
                    $cntMoney += $m['AMOUNT'];
                }*/
        $memberModel = new Member();
        foreach ($memberInfo as $k => $m) {
            $reqsn = $merId.$yesterday.getMillionString($k+1);
            $info = [
                'TRX_CODE'  => '100002',
                'VERSION'   => '03',
                'DATA_TYPE' => '2',
                'LEVEL'     => '6',
                'USER_NAME' => $config[ENV]['userName'],
                'USER_PASS' => $config[ENV]['password'],
                'REQ_SN'    => $reqsn,
            ];
            $tranSum = [
                'BUSINESS_CODE' => '09900',
                'MERCHANT_ID'   => $merId,
                'SUBMIT_TIME'   => date('YmdHis'),
                'TOTAL_ITEM'    => 1,
                'TOTAL_SUM'     => $m['AMOUNT']
            ];
            $transDetail = $m;

            $params = [
                'INFO' => $info,
                'BODY' => [
                    'TRANS_SUM' => $tranSum,
                    'TRANS_DETAILS' => [
                        'TRANS_DETAIL' => $transDetail,
                    ]
                ],
            ];

            zft_log('tonglianPayment', json_encode($params, JSON_UNESCAPED_UNICODE));
            $result = $batchTranx->sendRequest($params);
            //dd($result);
            zft_log('tonglianPayment', json_encode($result, JSON_UNESCAPED_UNICODE));
            if ($result != FALSE) {
                //echo  '验签通过，请对返回信息进行处理';
                //更新为处理中状态

                if ($result['AIPG']['INFO']['RET_CODE'] == '0000') {//成功状态
                    $update = $batchPayment->updateData(['pay_time' => $yesterday, 'mid' => $m['CUST_USERID'], 'status' => 0],
                        ['status' => 4, 'req_sn' => $reqsn, 'code' => $result['AIPG']['INFO']['RET_CODE']]);
                    if (!$update) {
                        zft_log('batchPayment', $batchPayment->getLastSql());
                    } else {
                        //更新冻结金额

                        //减少余额
                        $memberModel->modifyMemberMoney($m['CUST_USERID'], 0, 0, $m['PROTOCOL'], 1, 7, 0, 0, 41, '', $reqsn, 0, 0, true);
                        //新增冻结余额
                        $res = $memberModel->updateFreezeMoney($m['CUST_USERID'], 0, $m['PROTOCOL']);
                        if (!$res) {
                            zft_log('member_money', $memberModel->getLastSql());
                        }

                    }
                } else { //不成功
                    $update = $batchPayment->updateData(['pay_time' => $yesterday, 'mid' => $m['CUST_USERID'], 'status' => 0],
                        ['status' => 2, 'req_sn' => $reqsn, 'code' => $result['AIPG']['INFO']['RET_CODE'], 'msg' => $result['AIPG']['INFO']['ERR_MSG']]);
                    if (!$update) {
                        zft_log('batchPayment', $batchPayment->getLastSql());
                    }
                }

            } else {
                print_r("验签结果：验签失败，请检查证书是否正确");
            }
            unset($reqsn, $info, $transDetail, $tranSum, $params);

        }
    }

    /**
     * @comment 获取通联对账文件
     * @author wuhao
     */
    public function getTonglianPayFile()
    {
        $settDay = date('Ymd', strtotime('-1day'));  //清算日期(前一天)
        $reqTime = date('YmdHis');                   //获取的时间
        $month   = date('Ym', strtotime('-1day'));   //对应月份

        $config = parse_ini_file(HTML_DIR . '/extend/Business/TongLianBatchPayment/data/config.ini', true);
        //商户id
        $merId = $config[ENV]['merId'];
        //签名
        $data       = $settDay . '|' . $reqTime . '|' . $merId;
        $privateKey = file_get_contents($config[ENV]['privateKeyFile']);
        $pKeyId     = openssl_pkey_get_private($privateKey, $config[ENV]['password']);

        //dd($pKeyId, openssl_free_key($pKeyId));
        openssl_sign($data, $signature, $pKeyId);
        openssl_free_key($pKeyId);
        $sign = bin2hex($signature);
        //得到下载地址
        $url = $config[ENV]['apiDown'].'SETTDAY='.$settDay.'\\&REQTIME='.$reqTime.'\\&CONTFEE=1'.'\\&MERID='.$merId.'\\&SIGN='.$sign;
        $urlLog = $config[ENV]['apiDown'].'SETTDAY='.$settDay.'&REQTIME='.$reqTime.'&CONTFEE=1'.'&MERID='.$merId.'&SIGN='.$sign;
        zft_log('tonglianBatchPayment', $urlLog);

        //保存到服务器
        $command = "cd /var/www/html/zft/public/tonglianPay;mkdir -p ".$month.";chown -R nginx:nginx ".$month
            .";wget --no-check-certificate -O /var/www/html/zft/public/tonglianPay/".$month.'/'.$settDay.'.txt '.$url;
        exec($command, $res);
    }

    /**
     * @comment 处理通联对账文件
     * @author wuhao
     */
    public function handleTonglianFile()
    {
        $settDay = date('Ymd', strtotime('-1day'));  //清算日期(前一天)
        $month   = date('Ym', strtotime('-1day'));   //对应月份

        //查看有无文件
        $localUrl  = '/var/www/html/zft/public/tonglianPay/' . $month . '/' . $settDay . '.txt';
        if (!file_exists($localUrl)) {
            exit('无文件');
        }
        $file      = fopen($localUrl, 'r');
        $fileModel = new ExcelFile();
        if ($file) {
            //读取文件内容
            $i = 0;
            $data = [];
            while (!feof($file)) {
                $data[$i] = fgets($file);
                $i++;
            }
            fclose($file);

            //处理数据
            //新增到文件表(文件第一行不是数据)
            unset($data[0]);
            $data = array_merge($data);
            if (!$data || empty($data)) {
                exit('无数据');
            }

            $count   = count($data);                                            //导入记录数
            $saveUrl = str_replace(EXCEL_REMOVE_DIR, MAIN_DOMAIN, $localUrl);   //保存的url
            $fileId  = $fileModel->addFile($settDay.'.txt', 0, $saveUrl, date('Y-m-d H:i:s', strtotime($settDay)), $count, 5, 4);
            if (!$fileId) {
                zft_log('excel_file', $fileModel->getLastSql());
            }

            //新增到通联代付详情表

            //获取数据
            $list = [];
            foreach ($data as $k => $v) {
                $list[$k] = explode(' ', trim($v));
            }
            $collect = $pay = [];
            foreach ($list  as $a => $item) {
                $list[$a][6] = date('Y-m-d H:i:s', strtotime($item[6]));
                $list[$a][9] = (int) $item[9];
            }
            foreach ($list as $key => $value) {
                //0	交易批次号 Xml中的REQ_SN
                //1	交易序号	Xml中的SN
                //2	交易类型	0：代付   1：代收
                //3	交易状态	交易状态,参见附录定义
                //4	交易金额	单位分
                //5	对方账号	被付或被扣帐户
                //6	交易时间	格式YYYYMMDDhhmmss
                //7	结算日期	格式YYYYMMDD
                //8	自定义用户号 Xml中的CUST_USERID
                //9 手续费 下载对账文件时手续费为空时以0表示, CONTFEE为1时才包含该字段
                if ($value[2] == 1) {
                    $collect[] = $value;
                }
                else {
                    $pay[] = $value;
                }
            }
            //插入到通联对账明细表
            $insertData = [];
            foreach ($list as $v) {
                $insertData[] = [
                    'file_id'        => $fileId,
                    'req_sn'         => $v[0],
                    'sn'             => $v[1],
                    'type'           => $v[2],
                    'status'         => $v[3] == '0000' ? 1 : 0, //1处理成功  0处理失败
                    'code'           => $v[3],
                    'amount'         => $v[4],
                    'bank_card'      => $v[5],
                    'trade_time'     => $v[6],
                    'settle_time'    => $v[7],
                    'relevant_id'    => $v[8],
                    'service_charge' => $v[9],
                ];
            }
            $reconciliationModel = new Reconciliation();
            $res = $reconciliationModel->addAll($insertData);
            if (!$res) {
                zft_log('reconciliation', $reconciliationModel->getLastSql());
                exit();
            }

            //更新代付列表的状态
            $memberModel = new Member();
            $batchPayment = new BatchPayment();
            if ($pay) {
                foreach ($pay as $item) {
                    if ($item[3] == '0000') { //成功的
                        $update = $batchPayment->updateData(['mid' => $item[8],  'req_sn' => $item[0]],
                            ['status' => 1, 'code' => $item[3], 'settle_time' => $item[7], 'update_time' => time()]);

                        //更新冻结金额

                        //减少余额
                        //$memberModel->modifyMemberMoney($m['CUST_USERID'], 0, 0, $m['AMOUNT'], 1, 7, 0, 0, 41, '', $reqsn, 0, 0, true);
                        //更新冻结余额

                        //（实际提现金额+100）/ 费率  即提现金额
                        $res = $memberModel->updateFreezeMoney($item[8], 1, intval(($item[4]+$item[9]) / (1 - TONGLIAN_SERVICE)) );
                        if (!$res) {
                            zft_log('member_money', $memberModel->getLastSql());
                        }
                    } else {  //银行处理没通过的
                        $update = $batchPayment->updateData(['mid' => $item[8],  'req_sn' => $item[0]],
                            ['status' => 3, 'code' => $item[3], 'update_time' => time()]);
                        //更新冻结金额

                        //返还余额
                        $memberModel->modifyMemberMoney($item[8], 0, 0, intval(($item[4]+$item[9]) / (1 - TONGLIAN_SERVICE)), 0, 7, 0, 0, 41, '', $item[0], 0, 0, true);
                        //更新冻结余额
                        $res = $memberModel->updateFreezeMoney($item[8], 1, intval(($item[4]+$item[9]) / (1 - TONGLIAN_SERVICE)) );
                        if (!$res) {
                            zft_log('member_money', $memberModel->getLastSql());
                        }
                    }
                    if (!$update) {
                        zft_log('batch_payment', $batchPayment->getLastSql());
                    }
                }
            }
        } else {
            exit('无数据');
        }
    }

    /**
     * @comment 通联对账(对账前两天的)
     * @author wuhao
     */
    public function tonglianReconciliation()
    {
        $reconciliationModel = new Reconciliation();
        $batchPayment        = new BatchPayment();
        //$onlinePay           = new JournalOnline();
        $memberModel         = new Member();


        $time = date('Ymd', strtotime('-2days'));     //前天
        $yesterday = date('Ymd', strtotime('-1day')); //昨天

        //获取昨天对账明细(外部数据)
        $whereRecon = [
            'settle_time' => $yesterday,
        ];
        $reconList = $reconciliationModel->getList($whereRecon);

        //获取前天代付记录(内部数据)
        $whereBatch = [
            'pay_time' => $time,
        ];
        $batchList = $batchPayment->getList($whereBatch);

        //获取昨天在线交易记录(内部数据)
//        $whereOnline = [
//            'time'    => ['between', [strtotime($yesterday), strtotime($yesterday . ' +1day')]],//获取昨天的记录
//            'sourceT' => ['in', [2, 3]],                                              //通联的
//            'status'  => 1,       //已支付的
//        ];
//        $onlineList = $onlinePay->getList($whereOnline);


        if (!$batchList && !$reconList) {
            exit('无数据');
        }

        //获取所有的流水号
        $payReqsn =  [];
        if ($reconList) {
            foreach ($reconList as $a) {
                if ($a['type'] ==0) { //代付
                    $payReqsn[] = $a['req_sn'];
                }
//                else { //代收
//                    $incomeReqsn[] = $a['req_sn'];
//                }
            }
        }

        $batchSumList = [];
        if ($batchList) {
            $tmpIdArr = array_merge(array_unique(array_column($batchList, 'mid')));

            foreach ($tmpIdArr as $tmp) {
                $batchSumList[] = [
                    'mid' => $tmp,
                    'money' => 0
                ];
            }
            //dd($batchSumList);
            foreach ($batchSumList as $key => $bs) {
                foreach ($batchList as $b) {
                    if ($bs['mid'] == $b['mid']) {
                        $batchSumList[$key]['money'] += $b['actual_money'];
                        $batchSumList[$key]['pay_time'] = $b['pay_time'];
                        $batchSumList[$key]['req_sn'] = $b['req_sn'];
                        $batchSumList[$key]['status'] = $b['status'];
                        $batchSumList[$key]['settle_time'] = $b['settle_time'];
                    }
                }
            }

            foreach ($batchList as $b) {
                $payReqsn[] = $b['req_sn'];
            }
        }
//        if ($onlineList) {
//            foreach ($onlineList as $c) {
//                $incomeReqsn[] = $c['serial_number'];
//            }
//        }

        $payReqsn = array_merge(array_unique($payReqsn));     //代付流水
        // $incomeReqsn = array_merge(array_unique($incomeReqsn));//代收流水


        //详情列表
        $payList = [];
        if ($payReqsn) {  //代付列表
            foreach ($payReqsn as $k => $v) {
                $payList[$k][0] = $v;
            }
            foreach ($payReqsn as $k => $v) {
                foreach ($reconList as $a) {
                    if ($v == $a['req_sn']) {
                        $payList[$k][1] = $a;  //1是外部
                        break;
                    }
                }

                foreach ($batchSumList as $b) {
                    if ($v == $b['req_sn']) {
                        $payList[$k][2] = $b;
                        break;
                    }
                }
            }
        }

//        if ($incomeReqsn) {//获取代收列表
//            foreach ($incomeReqsn as $k => $v) {
//                $incomeList[$k][0] = $v;
//            }
//
//            foreach ($incomeReqsn as $k => $v) {
//                foreach ($reconList as $a) {
//                    if ($v == $a['req_sn']) {
//                        $incomeList[$k][1] = $a;  //1是外部数据
//                        break;
//                    }
//                }
//
//                foreach ($onlineList as $c) {
//                    if ($v == $c['serial_number']) {//2是内部数据
//                        $incomeList[$k][2] = $c;
//                        break;
//                    }
//                }
//            }
//        }


        //dd($payList);
        //内部数据个数，外部数据个数，内部金额总计，外部金额总计，差异数, 手续费
        $innerPaySum    = $outterPaySum    = $innerPayMoney    = $outterPayMoney    =  $payDiff    = $outterPayService = 0;
        //$innerIncomeSum = $outterIncomeSum = $innerIncomeMoney = $outterIncomeMoney =  $incomeDiff = $outterIncomeService = 0;
        if ($payList) {  //代付
            foreach ($payList as $p) {
                if (isset($p[1]) && $p[1]) {
                    $outterPaySum++;
                    $outterPayMoney += $p[1]['amount'];
                    $outterPayService += $p[1]['service_charge'];
                }
                if (isset($p[2]) && $p[2]) {
                    $innerPaySum++;
                    $innerPayMoney += $p[2]['money'];
                }

                if ((isset($p[1])  && !isset($p[2]))  || (!isset($p[1]) && isset($p[2])) ) {
                    //一个有一个无
                    $payDiff++;
                }
                if (isset($p[1]) && isset($p[2])) {
                    if ($p[1]['status'] == 0) { //交易失败的
                        $payDiff++;
                    } else {
                        //交易成功的算金额
                        if ($p[1]['amount'] + $p[1]['service_charge'] != $p[2]['money']) {
                            $payDiff++;
                        }
                    }
                }
            }

        }

        //代收记录
//        if ($incomeList) {
//            foreach ($incomeList as $p) {
//                if (isset($p[1]) && $p[1]) {
//                    $outterIncomeSum++;
//                    $outterIncomeMoney += $p[1]['amount'];
//                    $outterIncomeService += $p[1]['service_charge'];
//                }
//                if (isset($p[2]) && $p[2]) {
//                    $innerIncomeSum++;
//                    $innerIncomeMoney += $p[2]['money'];
//
//                }
//
//                if ((isset($p[1]) && !isset($p[2]))  || (!isset($p[1]) && isset($p[2])) ) {
//                    //一个有一个无
//                    $incomeDiff++;
//                }
//                if (isset($p[1]) && isset($p[2])) {
//                    if ($p[1]['status'] == 0) { //交易失败的
//                        $incomeDiff++;
//                    } else {
//                        //交易成功的算金额
//                        if ($p[1]['amount'] + $p[1]['service_charge'] != $p[2]['money']) {
//                            $incomeDiff++;
//                        }
//                    }
//                }
//            }
//        }


        $sheetTitle = ['财务报表', '对账明细'];
        $objPHPExcel     = load_excel();
        $objWriter       = new \PHPExcel_Writer_Excel5($objPHPExcel);
        for ($i = 0; $i < 2; $i++) {//生成两个sheet
            if ($i > 0) {
                $objPHPExcel->createSheet();
            }
            $objPHPExcel->setActiveSheetIndex($i);//设置工作sheet
            $objPHPExcel->getActiveSheet()->setTitle($sheetTitle[$i]); //设置工作表名称
            //都设置为文本格式
            $objPHPExcel->getActiveSheet()->getStyle('A:P')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
            if ($i ==0) {
                $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
                $objPHPExcel->getActiveSheet()->mergeCells('A2:F2');
                $objPHPExcel->getActiveSheet()->setCellValue('A1', '对账日期: '.$time);
                $objPHPExcel->getActiveSheet()->setCellValue('A2', '汇总记录');
                $objPHPExcel->getActiveSheet()->setCellValue('A3', '代付笔数');
                $objPHPExcel->getActiveSheet()->setCellValue('C3', '代付实际金额');
                $objPHPExcel->getActiveSheet()->setCellValue('E3', '代付手续费总额');
                $objPHPExcel->getActiveSheet()->setCellValue('B3', $outterPaySum);
                $objPHPExcel->getActiveSheet()->setCellValue('D3', yuan($outterPayMoney));
                $objPHPExcel->getActiveSheet()->setCellValue('F3', yuan($outterPayService));
            } else {
                $objPHPExcel->getActiveSheet()->mergeCells('A1:N1');
                $objPHPExcel->getActiveSheet()->mergeCells('A2:G2');
                $objPHPExcel->getActiveSheet()->mergeCells('H2:N2');
                $objPHPExcel->getActiveSheet()->setCellValue('A1', '对账日期: '.$time);
                $objPHPExcel->getActiveSheet()->setCellValue('A2', '外部数据');
                $objPHPExcel->getActiveSheet()->setCellValue('H2', '内部数据');
                $objPHPExcel->getActiveSheet()->setCellValue('A3', '交易流水');
                $objPHPExcel->getActiveSheet()->setCellValue('B3', '交易类型');
                $objPHPExcel->getActiveSheet()->setCellValue('C3', '交易状态');
                $objPHPExcel->getActiveSheet()->setCellValue('D3', '交易金额');
                $objPHPExcel->getActiveSheet()->setCellValue('E3', '对方账号');
                $objPHPExcel->getActiveSheet()->setCellValue('F3', '交易时间');
                $objPHPExcel->getActiveSheet()->setCellValue('G3', '手续费');
                $objPHPExcel->getActiveSheet()->setCellValue('H3', '交易流水');
                $objPHPExcel->getActiveSheet()->setCellValue('I3', '交易类型');
                $objPHPExcel->getActiveSheet()->setCellValue('J3', '交易状态');
                $objPHPExcel->getActiveSheet()->setCellValue('K3', '交易金额');
                $objPHPExcel->getActiveSheet()->setCellValue('L3', '对方账号');
                $objPHPExcel->getActiveSheet()->setCellValue('M3', '交易时间');
                $objPHPExcel->getActiveSheet()->setCellValue('N3', '手续费');

                $i = 4;
                $batchStatus = [
                    0 => '未处理',
                    1 => '处理成功',
                    2 => '通联请求未通过',
                    3 => '银行未通过',
                    4 => '处理中'
                ];
                if ($payList) { //代付记录
                    foreach ($payList as $p) {
                        //获取对方账号
                        $mid = $batchPayment->getList(['req_sn' => $p[0]], 'mid');
                        $username = $memberModel->getMemberInfoById($mid[0]['mid'], 'username');

                        if (isset($p[1]) && $p[1]) {//外部数据
                            $objPHPExcel->getActiveSheet()->setCellValue('A'.$i, '`'.$p[1]['req_sn']);
                            $objPHPExcel->getActiveSheet()->setCellValue('B'.$i, $p[1]['type'] == 0 ? '通联代付' : '通联代收');
                            $objPHPExcel->getActiveSheet()->setCellValue('C'.$i, $p[1]['status'] == 1 ? '处理成功' : '处理失败');
                            $objPHPExcel->getActiveSheet()->setCellValue('D'.$i, yuan($p[1]['amount']));
                            $objPHPExcel->getActiveSheet()->setCellValue('E'.$i, $username['username']);
                            $objPHPExcel->getActiveSheet()->setCellValue('F'.$i, $p[1]['settle_time']);
                            $objPHPExcel->getActiveSheet()->setCellValue('G'.$i, yuan($p[1]['service_charge']));
                        }

                        if (isset($p[2]) && $p[2]) {//内部数据
                            $objPHPExcel->getActiveSheet()->setCellValue('H'.$i, '`'.$p[2]['req_sn']);
                            $objPHPExcel->getActiveSheet()->setCellValue('I'.$i, '通联代付');
                            $objPHPExcel->getActiveSheet()->setCellValue('J'.$i, $batchStatus[$p[2]['status']]);
                            $objPHPExcel->getActiveSheet()->setCellValue('K'.$i, yuan($p[2]['money']));
                            $objPHPExcel->getActiveSheet()->setCellValue('L'.$i, $username['username']);
                            $objPHPExcel->getActiveSheet()->setCellValue('M'.$i, $p[2]['settle_time']);
                            $objPHPExcel->getActiveSheet()->setCellValue('N'.$i, 0);
                        }
                        $i++;
                    }
                }

//                if ($incomeList) {
//                    foreach ($incomeList as $v) {
//                        //获取对方账号
//                        $mid = $onlinePay->getList(['serial_number' => $v[0]], 'buyer_email');
//                        $username = $memberModel->getMemberInfoById($mid[0]['buyer_email'], 'username');
//
//                        if (isset($v[1]) && $v[1]) {//外部数据
//                            $objPHPExcel->getActiveSheet()->setCellValue('A'.$i, '`'.$v[1]['req_sn']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('B'.$i, $v[1]['type']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('C'.$i, $v[1]['status']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('D'.$i, yuan($v[1]['amount']));
//                            $objPHPExcel->getActiveSheet()->setCellValue('E'.$i, $username['username']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('F'.$i, $v[1]['settle_time']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('G'.$i, yuan($v[1]['service_charge']));
//                        }
//
//                        if (isset($v[2]) && $v[2]) {//内部数据
//                            $objPHPExcel->getActiveSheet()->setCellValue('H'.$i, '`'.$v[2]['serial_number']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('I'.$i, 0);
//                            $objPHPExcel->getActiveSheet()->setCellValue('J'.$i, $v[2]['status']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('K'.$i, yuan($v[2]['money']));
//                            $objPHPExcel->getActiveSheet()->setCellValue('L'.$i, $username['username']);
//                            $objPHPExcel->getActiveSheet()->setCellValue('M'.$i, date('Ymd', $v[2]['time']));
//                            $objPHPExcel->getActiveSheet()->setCellValue('N'.$i, 0);
//                        }
//                        $i++;
//                    }
//                }
            }
        }

        $fileName = '对账明细'.date('Ymd',strtotime('-2day')).'.xls';
        $year = date('Y', strtotime('-2day'));
        $month = date('m',strtotime('-2day'));
        $day = date('d',strtotime('-2day'));
        $time = $year.'/'.$month.'/'.$day;
        $pathStr = EXCEL_IMPORT_DIR.'reconciliation/' . $time;
        $downloadStr = MAIN_DOMAIN.'excel/reconciliation/' . $time;
        createDir($pathStr);
        $objWriter->save($pathStr.'/'.$fileName);
        $url =  $downloadStr.'/'.$fileName;

        $res1 = $reconciliationModel->addResult(0, 0, date('Ymd', strtotime('-2days')), $innerPayMoney, $innerPaySum, $payDiff ==0 ? 1 : 0, $payDiff, $url);
        if (!$res1) {
            zft_log('reconciliation', $reconciliationModel->getLastSql());
        }
//        $res2 = $reconciliationModel->addResult(0, 1, $yesterday, $innerIncomeMoney, $innerIncomeSum, $incomeDiff ==0 ? 1 : 0, $incomeDiff, $url);
//        if (!$res2) {
//            zft_log('reconciliation', $reconciliationModel->getLastSql());
//        }
        exit('success');
    }

}
